#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复验证：知识搜索向量恢复的健壮性

用例目的：
- 当ChromaDBClient._connected=True但底层client为None时，_restore_vectors_from_chromadb应安全跳过并记录warning，不应向内存向量存储写入。
"""

import sys
from pathlib import Path
import pytest
import pytest_asyncio
from loguru import logger

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.core.knowledge_processor import KnowledgeProcessor
from src.database.manager import DatabaseManager
from src.config import load_config


@pytest.mark.asyncio
async def test_当chromadb_client为None实例时跳过恢复():
    config = load_config()
    db_manager = DatabaseManager(config)
    await db_manager.initialize()
    try:
        kp = KnowledgeProcessor(db_manager, config)
        await kp.initialize()

        # 保证vectorizer与其vector_store存在
        assert kp.vectorizer is not None
        assert kp.vectorizer.vector_store is not None

        # 记录初始向量数量（仅当InMemoryVectorStore有vectors属性时检查）
        vs = kp.vectorizer.vector_store
        initial_count = len(getattr(vs, 'vectors', [])) if hasattr(vs, 'vectors') else None

        # 构造场景：标记chromadb已连接但底层client置空
        chroma = db_manager.chromadb_client
        if chroma is None:
            pytest.skip("测试跳过：chromadb_client未初始化")
        chroma._connected = True
        # 强制将底层client设为None，模拟依赖缺失等情况
        chroma.client = None

        # 执行恢复
        await kp._restore_vectors_from_chromadb()

        # 恢复后不应新增向量
        if hasattr(vs, 'vectors') and initial_count is not None:
            assert len(vs.vectors) == initial_count, "在client为None的情况下不应写入向量"
    finally:
        await kp.shutdown()
        await db_manager.shutdown()